const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();


/**
 * 获取所有仓库
 */
exports.getAllWarehouses = async (req, res) => {
  try {
    const warehouses = await prisma.warehouse.findMany({
      include: {
        manager: {
          select: {
            id: true,
            name: true,
            username: true
          }
        }
      }
    });
    
    return res.status(200).json({
      success: true,
      data: warehouses
    });
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取仓库列表失败',
      error: error.message
    });
  }
};

/**
 * 获取单个仓库详情
 */
exports.getWarehouseById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: Number(id) },
      include: {
        manager: {
          select: {
            id: true,
            name: true,
            username: true
          }
        }
      }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    return res.status(200).json({
      success: true,
      data: warehouse
    });
  } catch (error) {
    console.error('获取仓库详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取仓库详情失败',
      error: error.message
    });
  }
};

/**
 * 创建仓库
 */
exports.createWarehouse = async (req, res) => {
  try {
    const { name, location, managerId, contact, status, remarks } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '仓库名称不能为空'
      });
    }
    
    const existingWarehouse = await prisma.warehouse.findFirst({
      where: { name }
    });
    
    if (existingWarehouse) {
      return res.status(400).json({
        success: false,
        message: '仓库名称已存在'
      });
    }
    
    const warehouse = await prisma.warehouse.create({
      data: {
        name,
        location,
        managerId: managerId ? Number(managerId) : null,
        contact,
        status: status !== undefined ? Boolean(status) : true,
        remarks
      }
    });
    
    // 记录审计日志
    await logAudit({
      userId: req.user.id,
      action: 'create',
      module: 'warehouse',
      description: `创建仓库 "${name}"`,
      details: JSON.stringify(warehouse)
    });
    
    return res.status(201).json({
      success: true,
      data: warehouse,
      message: '仓库创建成功'
    });
  } catch (error) {
    console.error('创建仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '创建仓库失败',
      error: error.message
    });
  }
};

/**
 * 更新仓库
 */
exports.updateWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, location, managerId, contact, status, remarks } = req.body;
    
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: Number(id) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    if (name) {
      const existingWarehouse = await prisma.warehouse.findFirst({
        where: {
          name,
          id: {
            not: Number(id)
          }
        }
      });
      
      if (existingWarehouse) {
        return res.status(400).json({
          success: false,
          message: '仓库名称已存在'
        });
      }
    }
    
    const updatedWarehouse = await prisma.warehouse.update({
      where: { id: Number(id) },
      data: {
        name: name || warehouse.name,
        location: location !== undefined ? location : warehouse.location,
        managerId: managerId !== undefined ? (managerId ? Number(managerId) : null) : warehouse.managerId,
        contact: contact !== undefined ? contact : warehouse.contact,
        status: status !== undefined ? Boolean(status) : warehouse.status,
        remarks: remarks !== undefined ? remarks : warehouse.remarks
      }
    });
    
    // 记录审计日志
    await logAudit({
      userId: req.user.id,
      action: 'update',
      module: 'warehouse',
      description: `更新仓库 "${updatedWarehouse.name}"`,
      details: JSON.stringify({
        before: warehouse,
        after: updatedWarehouse
      })
    });
    
    return res.status(200).json({
      success: true,
      data: updatedWarehouse,
      message: '仓库更新成功'
    });
  } catch (error) {
    console.error('更新仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '更新仓库失败',
      error: error.message
    });
  }
};

/**
 * 删除仓库
 */
exports.deleteWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: Number(id) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    // 检查仓库是否有关联的库存记录
    const inventoryCount = await prisma.inventoryRecord.count({
      where: { warehouseId: Number(id) }
    });
    
    if (inventoryCount > 0) {
      return res.status(400).json({
        success: false,
        message: '仓库已有库存记录，无法删除'
      });
    }
    
    // 检查仓库是否有关联的入库单
    const stockInCount = await prisma.stockInOrder.count({
      where: { warehouseId: Number(id) }
    });
    
    if (stockInCount > 0) {
      return res.status(400).json({
        success: false,
        message: '仓库已有入库单记录，无法删除'
      });
    }
    
    // 检查仓库是否有关联的出库单
    const stockOutCount = await prisma.stockOutOrder.count({
      where: { warehouseId: Number(id) }
    });
    
    if (stockOutCount > 0) {
      return res.status(400).json({
        success: false,
        message: '仓库已有出库单记录，无法删除'
      });
    }
    
    // 如果没有关联记录，可以删除仓库
    await prisma.warehouse.delete({
      where: { id: Number(id) }
    });
    

    
    return res.status(200).json({
      success: true,
      message: '仓库删除成功'
    });
  } catch (error) {
    console.error('删除仓库失败:', error);
    return res.status(500).json({
      success: false,
      message: '删除仓库失败',
      error: error.message
    });
  }
};

/**
 * 获取仓库库存情况
 */
exports.getWarehouseInventory = async (req, res) => {
  try {
    const { id } = req.params;
    
    const warehouse = await prisma.warehouse.findUnique({
      where: { id: Number(id) }
    });
    
    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: '仓库不存在'
      });
    }
    
    // 获取仓库中的库存记录，包含商品信息
    const inventoryRecords = await prisma.inventoryRecord.findMany({
      where: { warehouseId: Number(id) },
      include: {
        product: {
          select: {
            id: true,
            name: true,
            description: true,
            imageUrl: true,
            stockUnit: true,
            costPrice: true,
            price: true,
            category: true
          }
        }
      }
    });
    
    return res.status(200).json({
      success: true,
      data: {
        warehouse,
        inventory: inventoryRecords
      }
    });
  } catch (error) {
    console.error('获取仓库库存失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取仓库库存失败',
      error: error.message
    });
  }
}; 